import json
import time
import datetime
import argparse
import os
from pathlib import Path
import winsound  # 仅Windows

class TaskManager:
    def __init__(self, data_file='tasks.json'):
        self.data_file = data_file
        self.tasks = self.load_tasks()
    
    def load_tasks(self):
        """加载任务数据"""
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except:
                return []
        return []
    
    def save_tasks(self):
        """保存任务数据"""
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(self.tasks, f, ensure_ascii=False, indent=2)
    
    def add_task(self, content, priority='medium', due_date=None):
        """添加新任务"""
        task = {
            'id': len(self.tasks) + 1,
            'content': content,
            'priority': priority.lower(),
            'due_date': due_date,
            'completed': False,
            'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        self.tasks.append(task)
        self.save_tasks()
        print(f"已添加任务 (ID: {task['id']})")
    
    def list_tasks(self, show_completed=False, priority=None):
        """列出任务"""
        if not self.tasks:
            print("没有任务")
            return
        
        filtered = self.tasks
        if not show_completed:
            filtered = [t for t in filtered if not t['completed']]
        if priority:
            filtered = [t for t in filtered if t['priority'] == priority.lower()]
        
        print(f"共 {len(filtered)} 个任务:")
        for task in filtered:
            status = "✓" if task['completed'] else " "
            priority_tag = {
                'high': '❗',
                'medium': '🔹',
                'low': '🔽'
            }.get(task['priority'], '')
            
            due_str = f" [截止: {task['due_date']}]" if task['due_date'] else ""
            print(f"[{status}] {task['id']}. {priority_tag} {task['content']}{due_str}")
    
    def complete_task(self, task_id):
        """标记任务为完成"""
        for task in self.tasks:
            if task['id'] == task_id:
                task['completed'] = True
                self.save_tasks()
                print(f"已完成任务: {task_id}")
                return
        print(f"未找到任务 ID: {task_id}")
    
    def check_reminders(self):
        """检查需要提醒的任务"""
        now = datetime.datetime.now().strftime('%Y-%m-%d')
        reminders = []
        
        for task in self.tasks:
            if not task['completed'] and task['due_date']:
                # 检查是否今天到期或已过期
                if task['due_date'] <= now:
                    reminders.append(task)
        
        return reminders

def reminder_daemon(interval=300):
    """定时提醒守护进程"""
    manager = TaskManager()
    print("任务提醒程序已启动（按Ctrl+C退出）")
    
    try:
        while True:
            reminders = manager.check_reminders()
            if reminders:
                print("\n=== 任务提醒 ===")
                for task in reminders:
                    print(f"❕ 任务 {task['id']}: {task['content']} (截止: {task['due_date']})")
                
                # 播放提醒音
                try:
                    winsound.Beep(1000, 800)
                    time.sleep(0.2)
                    winsound.Beep(1200, 800)
                except:
                    pass
            
            # 等待指定间隔
            time.sleep(interval)
    
    except KeyboardInterrupt:
        print("\n提醒程序已退出")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='任务提醒与待办事项工具')
    parser.add_argument('action', choices=['add', 'list', 'complete', 'reminder'], 
                      help='操作：add(添加)、list(列表)、complete(完成)、reminder(提醒)')
    parser.add_argument('--content', help='任务内容（add时需要）')
    parser.add_argument('--priority', choices=['high', 'medium', 'low'], default='medium', 
                      help='任务优先级')
    parser.add_argument('--due', help='截止日期 (YYYY-MM-DD)')
    parser.add_argument('--id', type=int, help='任务ID（complete时需要）')
    parser.add_argument('--interval', type=int, default=300, help='提醒间隔(秒)')
    parser.add_argument('--show-completed', action='store_true', help='显示已完成任务')
    
    args = parser.parse_args()
    manager = TaskManager()
    
    if args.action == 'add':
        if not args.content:
            print("请指定任务内容 --content")
        else:
            manager.add_task(args.content, args.priority, args.due)
    elif args.action == 'list':
        manager.list_tasks(args.show_completed)
    elif args.action == 'complete':
        if not args.id:
            print("请指定任务ID --id")
        else:
            manager.complete_task(args.id)
    elif args.action == 'reminder':
        reminder_daemon(args.interval)
